#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui

from pylot.core import (Collection, LEVELS)

from _pylot.qtgui.interfaces.widgetinterface import WidgetInterface
from _pylot.qtgui.misc import load_designer_file
from _pylot.qtgui.widgets.gui_collectioneditor import GuiCollectionEditor
from _pylot.qtgui.widgets.gui_autopreferences import GuiAutoPrefs

class GuiAutoWidget(WidgetInterface):
  def __init__ (self, handler=None):
    WidgetInterface.__init__(self, handler)
    QtGui.QWidget.__init__(self)

  def autoCreateMenus(self, pylot_widget):
    u"""
    Generates menus by concatenating child menus
    """
    main_menu = QtGui.QMenu(self._plugin_path.name)
    for menu in pylot_widget.menus :
      main_menu.addMenu(menu)
    self.addMenu_(main_menu)

  def autoCreateToolBars(self, pylot_widget):
    u"""
    Generates toolbars by concatenating child toolbars
    """
    for tool_bar in pylot_widget.tool_bars :
      self.addToolBar_(tool_bar)

  def autoCreatePreferences(self, pylot_widget):
    u"""
    Generates preference widget by concatenating child preference widget
    """
    plugin_pref = pylot_widget.pref

    if not isinstance(self.pref, GuiAutoPrefs) :
      self.pref = GuiAutoPrefs(handler=self.handler)

    if plugin_pref :
      self.pref.addPrefWidget(plugin_pref)

  def autoCreatePreferenceWidget(self):
    if self.handler.hasUserOptions() :
      pref = GuiAutoPrefs(handler=self.handler)
      pref_widgets = []
      for user_options in self.handler._user_options :
        widget = GuiCollectionEditor(user_options, handler=self.handler)
        setattr(pref, user_options.name, widget)
        pref.addPrefWidget(widget)
      self._pref = pref

  def _createPreferences(self):
    self.autoCreatePreferenceWidget()

  def addPlugin(self, name, handler=None, plugin_id=None, auto_fill_widget=True):
    gui = WidgetInterface.addPlugin(self, name, handler, plugin_id,
                                    auto_fill_widget)
    if auto_fill_widget is True :
      self.autoCreateToolBars(gui)
      self.autoCreateMenus(gui)
      self.autoCreatePreferences(gui)
    return gui

